<template>
  <el-row class="main-row" gutter="10">
    <!-- 左侧图片区域 -->
    <el-col :span="18" class="left-col">
      <ContentWrap class="left-wrap" v-loading="imageLoading">
        <div class="image-wrapper">
          <img
            :src="imageUrl"
            class="centered-img"
            :alt="submitForm.taskTypeName"
          />
        </div>
      </ContentWrap>
    </el-col>
    <!-- 右侧表单区域 -->
    <el-col :span="6" class="right-col ">
      <ContentWrap class="right-wrap">
        <el-form :model="submitForm" ref="taskSubmitFromRef" label-width="120px">
          <UploadExcelCard
            v-model:fileList="inputFileList"
            :exampleXlsx="excelUrl"
            :submitted="submitted"
            :maxFileSize="5 * 1024 * 1024"
            :header="'输入文件'"
          />
          <ProjectInfoCard v-model="submitForm" :submitted="submitted" />
          <GroupedBarplotCard v-model="submitForm" :submitted="submitted"/>
          <PlotCard v-model="submitForm" :submitted="submitted"/>
          <LegendCard v-model="submitForm" :submitted="submitted"/>
          <AxisXCard  v-model="submitForm" :submitted="submitted"/>
          <AxisYCard  v-model="submitForm" :submitted="submitted"/>
        </el-form>
        <!-- 操作按钮区域 -->
        <el-form-item>
          <el-button v-if="!submitted" type="primary" @click="handleSubmitTask" size="large">提交</el-button>
          <el-button v-if="submitted" type="danger" @click="handleUpdateResult" size="large">更新</el-button>
          <el-button v-if="submitted" type="warning" @click="handleResetResult" size="large">重置</el-button>
          <el-button v-if="submitted" type="info" @click="handleDownloadResult" size="large">下载</el-button>
        </el-form-item>
      </ContentWrap>
    </el-col>
  </el-row>
</template>


<script lang="ts" setup>
import {defineOptions, reactive, ref} from "vue";
import type {UploadUserFile} from 'element-plus'
import * as PlotApi from "@/api/biobee/plot";
import {useRoute, useRouter}    from "vue-router";
import { useTagsViewStore } from '@/store/modules/tagsView';
import ProjectInfoCard from "@/components/MyCards/ProjectInfoCard.vue";
import PlotCard from "@/components/MyCards/PlotCard.vue";
import AxisXCard from "@/components/MyCards/AxisXCard.vue";
import UploadExcelCard from "@/components/MyCards/UploadExcelCard.vue";
import GroupedScatterCard from "@/components/MyCards/GroupedScatterCard.vue";

defineOptions({ name: "GroupedScatter" });
const router = useRouter()
const submitForm = reactive<any>({});
const imageUrl = ref<string | null>(null);
const excelUrl = ref<string | null>(null);
const props = defineProps({projectId: String, taskId: String})
const submitted = ref(false)
const imageLoading = ref(false)
const message = useMessage() // 消息弹窗
const inputFileList = ref<UploadUserFile[]>([])
const taskSubmitFromRef = ref<any>(null);


const downloadResultImage = async () => {
  try{
    const imageBlobRes  = await PlotApi.downloadResult({
      projectId: submitForm.projectId,
      taskId: submitForm.taskId,
      fileName: "result.png"
    })
    const blob = imageBlobRes as unknown as Blob
    if (imageUrl.value) {
      URL.revokeObjectURL(imageUrl.value)
    }
    // 生成并赋值预览 URL
    imageUrl.value = URL.createObjectURL(blob)
  } catch (err){
    ElMessage.error("下载结果图片失败")
  }
}

const downloadResultConfig = async() => {
  try {
    const jsonBlobRes  = await PlotApi.downloadResult({
      projectId: submitForm.projectId,
      taskId: submitForm.taskId,
      fileName: "result.json"
    })
    Object.assign(submitForm, jsonBlobRes);
  } catch {
    ElMessage.error("下载结果配置文件失败")
  }
}

const downloadExampleImage = async () => {
  try{
    const imageBlobRes = await PlotApi.downloadExample({
      projectType:"Barplot",
      taskType: "GroupedBarplot",
      fileName: "example.png"
    })
    const imageBlob = imageBlobRes as unknown as Blob
    if (imageUrl.value) {
      URL.revokeObjectURL(imageUrl.value)
    }
    // 生成并赋值预览 URL
    imageUrl.value = URL.createObjectURL(imageBlob)
  } catch (err){
    ElMessage.error("下载示例图片失败")
  }
}

const downloadExampleConfig = async() => {
  try{
    const jsonBlobRes  = await PlotApi.downloadExample({
      projectType:"Barplot",
      taskType: "GroupedBarplot",
      fileName: "example.json"
    })
    Object.assign(submitForm, jsonBlobRes);
  }catch (err){
    ElMessage.error("下载示例配置文件失败")
  }
}


const downloadExampleInput = async() => {
  try {
    const excelBlobRes = await PlotApi.downloadExample({
      projectType:"Barplot",
      taskType: "GroupedBarplot",
      fileName: "example.xlsx"
    })
    const excelBlob = excelBlobRes as unknown as Blob
    if (excelUrl.value) {
      URL.revokeObjectURL(excelUrl.value)
    }
    // 生成并赋值预览 URL
    excelUrl.value = URL.createObjectURL(excelBlob)
  } catch {
    ElMessage.error("下载示例输入文件失败")
  }
}

// 点击更新结果
const handleUpdateResult = async () =>{
  imageLoading.value = true
  try{
    await PlotApi.submitTask(submitForm);
    await downloadResultImage();
    await downloadResultConfig();
    ElMessage.success(`更新成功`)
  }catch{
    message.error(`更新失败`)
  } finally {
    imageLoading.value = false
  }
}

const viewExample = async () => {
  imageLoading.value = true;
  try{
    await downloadExampleConfig();
    await downloadExampleImage();
    await downloadExampleInput();
  }catch (err){
    ElMessage.error('操作失败');
  } finally {
    imageLoading.value = false;
  }
}

const viewResult = async () => {
  imageLoading.value = true
  try {
    await downloadResultConfig();
    await downloadResultImage();
    submitted.value = true
  } catch(e) {
    ElMessage.error("操作失败")
  } finally {
    imageLoading.value = false;
  }
}

// 下载结果
const handleDownloadResult = async () => {
  try {
    imageLoading.value = true
    const blobRes = await PlotApi.downloadResult({
      projectId: submitForm.projectId,
      taskId: submitForm.taskId,
      fileName: "result.zip"
    });
    const blob = blobRes as Blob;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${submitForm.projectName}-${submitForm.taskName}.zip`;
    link.click();
    URL.revokeObjectURL(link.href);
  } catch (error) {
    message.error("下载失败");
  } finally {
    imageLoading.value = false
  }
};

const handleSubmitTask = async () =>{
  imageLoading.value = true
  try{
    submitForm.inputFile = inputFileList.value[0].name
    const formData = new FormData()
    formData.append("file", inputFileList.value[0].raw)
    formData.append('projectId', submitForm.projectId)
    formData.append('taskId', submitForm.taskId)
    await PlotApi.uploadFile(formData);
    await PlotApi.submitTask(submitForm)
    await downloadResultImage();
    await downloadResultConfig();
    submitted.value = true
    message.success(`提交成功`)
  }catch(err){
    message.error(`提交失败`)
  }finally {
    imageLoading.value = false
  }
}

const handleResetResult = async() => {
  try {
    await downloadResultConfig()
    ElMessage.success("重置成功");
  } catch{
    ElMessage.error("重置失败");
  }
}

if (onMounted) {
  /** 初始化 */
  onMounted(async () => {
      if (props.projectId && props.taskId) {
        console.log("组件渲染")
        submitForm.projectId = props.projectId
        submitForm.taskId = props.taskId
        await viewResult()
      } else {
        console.log("路由跳转")
        const route = useRoute()  // 获取当前路由信息
        if (route.query.projectId && route.query.taskId) {
          submitForm.projectId = String(route.query.projectId)
          submitForm.taskId = String(route.query.taskId)
          await viewResult()
          const tagsViewStore = useTagsViewStore()
          const currentView = tagsViewStore.getVisitedViews.find(v => v.fullPath === route.fullPath)
          if ("meta" in currentView) {
            currentView.meta.title = submitForm.taskName;
          }
        } else {
          console.log("直接渲染")
          await viewExample();
          submitForm.projectId = `${submitForm.projectType}_${Math.random().toString(36).substr(2, 16)}`
          submitForm.taskId = `${submitForm.taskType}_${Math.random().toString(36).substr(2, 16)}`
        }
      }
    }
  )
}


</script>
<style scoped>
.main-row {
  width: 100%;
  height: 87vh; /* 设置父容器的固定高度 */
  display: flex; /* 启用 Flexbox，使子列等高 */
  align-items: stretch; /* 确保 flex 项在垂直方向上拉伸填满父容器 */
}

.left-col,
.right-col {
  height: 100%; /* 让 el-col 占满父 el-row 的高度 */
  display: flex; /* 使 el-col 成为 Flex 容器，以便其子元素 (ContentWrap) 可以填充它 */
  flex-direction: column; /* 让子元素 (ContentWrap) 沿垂直方向排列，以便占据整个高度 */
}

.left-wrap {
  flex-grow: 1; /* 允许 ContentWrap 占用父容器 (el-col) 的所有可用空间 */
  width: 100%; /* 让 ContentWrap 占用父容器 (el-col) 的全部宽度 */

  /* **以下是让图片在 ContentWrap 内部水平垂直居中的关键 Flexbox 属性** */
  display: flex; /* 将 ContentWrap 设为 Flex 容器 */
  align-items: center;   /* 垂直居中其内容（图片）*/
  justify-content: center; /* 水平居中其内容（图片）*/

  box-sizing: border-box; /* 确保 padding 和 border 不会增加元素总尺寸 */
  overflow: hidden; /* **保留这个，作为最终的保障，以防任何意外的像素溢出** */
}

.right-wrap{
  flex-grow: 1; /* 允许 ContentWrap 占用父容器 (el-col) 的所有可用空间 */
  width: 100%; /* 让 ContentWrap 占用父容器 (el-col) 的全部宽度 */
  box-sizing: border-box; /* 确保 padding 和 border 不会增加元素总尺寸 */
  overflow-y: auto; /* **保留这个，作为最终的保障，以防任何意外的像素溢出** */
}

.centered-img {
  /* **核心：确保图片完整显示，不裁剪，不溢出，并保持宽高比** */
  max-width: 100%;  /* 图片最大宽度为其父容器宽度的 100% */
  height: 85vh;
  width: auto;
  object-fit: contain; /* **核心：保持图片纵横比，并将图片完全包含在容器内** */
  display: block; /* 确保图片是块级元素，避免一些潜在的空白或布局问题 */
}
</style>

